package xin.yangshuai.springsecurity01.controller;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import xin.yangshuai.common01.entity.BaseResult;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@Controller
public class IndexController {

    @RequestMapping
    public String index() {
        return "index";
    }

    @GetMapping("info")
    @ResponseBody
    public BaseResult info() {

        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        Object principal = authentication.getPrincipal();
        // credentials为null，做了脱敏处理
        Object credentials = authentication.getCredentials();
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

        String name = authentication.getName();

        Map<String, Object> data = new HashMap<>();
        data.put("username", name);
        data.put("authorities", authorities);

        BaseResult<Object> result = new BaseResult<>();
        result.setCode("200");
        result.setData(data);

        return result;
    }
}